import router from '@/router'
import { asyncRoutes } from './router/asyncRoutes'
import { getToken } from '@/utils/auth'
import store from './store'

const WHITE_LIST = ['/login', '/404']

function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  if (firstRoutePerms.includes('*')) {
    return asyncRoutes
  }
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    return {
      ...item,
      children: item.children.filter(child => {
        return secondRoutePerms.includes(child.permission)
      })
    }
  })
}

router.beforeEach(async(to, from, next) => {
  const token = getToken()
  if (token) {
    next()
    if (!store.state.user.userProfile.id) {
      const res = await store.dispatch('user/getUserProfile')
      const firstRoutePerms = getFirstRoutePerms(res)
      const secondRoutePerms = getSecondRoutePerms(res)
      const routes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      routes.forEach(route => {
        router.addRoute(route)
      })
      store.commit('menu/setMenuList', routes)
    }
  } else {
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
